package com.windoent.yugioh.ui.activity.point;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.brvah.SeasonRewardAddressAdapter;
import com.windoent.yugioh.base.BaseActivity;
import com.windoent.yugioh.bean.GoodsAddressListBean;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.ui.activity.meinfo.AddAddressActivty;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.ActivityTitle;
import com.windoent.yugioh.widget.dialog.SeasonRewardAddressSureDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;

import java.util.List;

import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/5/14 10:02
 * desc   :赛季奖励选择地址
 */
public class SelectSeasonRewardGetAddressActivity extends BaseActivity {
    private ActivityTitle mActivityTitle;
    private LinearLayout mLlAddAddress;
    private Button mBtnGetCode;
    private SmartRefreshLayout mSmartLayout;
    private RecyclerView mRecyclerView;
    private String limit = Constants.PAGETEN;
    private int mCount = 1;
    private int positionSelect = 0;
    private SeasonRewardAddressAdapter adapter;

    @Override
    public int getLayout() {
        return R.layout.activity_point_select_address_get_reward;
    }

    @Override
    public void initView() {
        super.initView();

        mActivityTitle = (ActivityTitle) findViewById(R.id.activity_title);
        immersiveStatusBar(mActivityTitle.getView());
        mLlAddAddress = (LinearLayout) findViewById(R.id.ll_add_address);
        mBtnGetCode = (Button) findViewById(R.id.btn_get_code);
        mSmartLayout = (SmartRefreshLayout) findViewById(R.id.smart_layout);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mLlAddAddress.setVisibility(View.GONE);
        mBtnGetCode.setText(getString(R.string.string_add_new_address));
    }

    @Override
    public void initData() {
        super.initData();
        initAdapter();
        initRefreshData("");
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this, "赛季奖励选择地址界面");
        fresh("");
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "赛季奖励选择地址界面");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }

    @Override
    public void initListener() {
        super.initListener();
        mActivityTitle.setBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mLlAddAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, AddAddressActivty.class);
                intent.putExtra("add_address", true);
                startActivity(intent);
            }
        });
        mBtnGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (adapter != null) {
                    List<GoodsAddressListBean.DataBean.ResBean> data = adapter.getData();
                    boolean hasData = (data != null && data.size() > 0);
                    if (hasData) {
                        //提交
                        showGetRewardAddressDialog();
                    } else {
                        Intent intent = new Intent(mContext, AddAddressActivty.class);
                        intent.putExtra("add_address", true);
                        startActivity(intent);
                    }
                } else {
                    Intent intent = new Intent(mContext, AddAddressActivty.class);
                    intent.putExtra("add_address", true);
                    startActivity(intent);
                }
            }
        });
    }

    //信息确认对话框
    private void showGetRewardAddressDialog() {
        List<GoodsAddressListBean.DataBean.ResBean> data = adapter.getData();
        if (data != null) {
            GoodsAddressListBean.DataBean.ResBean bean = data.get(positionSelect);
            if (bean != null) {
                SeasonRewardAddressSureDialog dialog = new SeasonRewardAddressSureDialog(mContext);
                dialog.setNameStr(BaseMethod.notNullDefaultValueNull(bean.getName()));
                dialog.setPhoneStr(BaseMethod.notNullDefaultValueNull(bean.getTelephone()));
                dialog.setAreaStr(BaseMethod.notNullDefaultValueNull(bean.getAddress()));
                dialog.setOnclickListener(new SeasonRewardAddressSureDialog.onSureOnclickListener() {
                    @Override
                    public void onGetRewardClick() {
                        receiveReward(bean.getId() + "");
                    }
                });
                dialog.show();
            } else {
                ToastUtils.showText(getString(R.string.string_select_youxiao_address));
            }
        } else {
            ToastUtils.showText(getString(R.string.string_select_youxiao_address));
        }
    }

    //奖励领取
    private void receiveReward(String address_id) {
        showLoadingDialog("");
        PhoneLive.receiveReward(getUserToken(), address_id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            //提交成功
                            startActivity(new Intent(mContext, SeasonRewardSubmitActivity.class));
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    private void initRefreshData(String text) {
        //下拉刷新
        mSmartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                fresh(text);
            }
        });
        //加载更多
        mSmartLayout.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//                loadMore(text);
            }
        });
    }

    private void loadMore(String text) {
        mCount = mCount + 1;
        getSeasonRewardAddressList(text, mCount + "", limit, false);
    }

    private void fresh(String text) {
        mCount = 1;
        getSeasonRewardAddressList(text, mCount + "", limit, true);
    }

    private void initAdapter() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new SeasonRewardAddressAdapter();
        adapter.setEmptyView(LayoutInflater.from(this).inflate(R.layout.recycler_view_address_empty, mRecyclerView, false));
        adapter.setAnimationEnable(false);
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {
                positionSelect = position;
                adapter.setPosition(positionSelect);
            }
        });

    }

    //dizhi列表
    private void getSeasonRewardAddressList(String title, String page, String limit, boolean first) {
        showLoadingDialog("");
        PhoneLive.getAddressList(getUserToken(), page, limit, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
                freshFail(first);
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            GoodsAddressListBean json = gson.fromJson(response, GoodsAddressListBean.class);
                            if (json != null) {
                                GoodsAddressListBean.DataBean data = json.getData();
                                if (data != null) {
                                    List<GoodsAddressListBean.DataBean.ResBean> res = data.getRes();
                                    boolean hasData = (res != null && res.size() > 0);
                                    mLlAddAddress.setVisibility(hasData ? View.VISIBLE : View.GONE);
                                    mBtnGetCode.setText(getString(hasData ? R.string.string_sure_submit : R.string.string_add_new_address));
                                    if (res != null) {
                                        if (first) {
                                            adapter.setNewInstance(res);
                                            mSmartLayout.finishRefresh(true);
                                            if (res.size() >= positionSelect) {
                                                adapter.setPosition(positionSelect);
                                            }
                                        } else {
                                            adapter.addData(res);
                                            mSmartLayout.finishLoadMore(true);
                                        }
                                    } else freshFail(first);
                                } else freshFail(first);
                            } else freshFail(first);
                        } else freshFail(first);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        freshFail(first);
                    }
                } else {
                    freshFail(first);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });

    }

    //刷新失败
    private void freshFail(boolean fresh) {
        if (fresh) {
            adapter.setNewInstance(null);
            mSmartLayout.finishRefresh(false);
        } else {
            mSmartLayout.finishLoadMore(false);
        }
    }

}
